package pub.guoxin.oops.manager.controller;

import io.swagger.annotations.ApiOperation;
import org.assertj.core.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import pub.guoxin.oops.annotation.InjectUser;
import pub.guoxin.oops.constants.OopsPathConstants;
import pub.guoxin.oops.manager.service.CompanyService;
import pub.guoxin.oops.manager.vo.CompanyVo;
import pub.guoxin.oops.model.Company;
import pub.guoxin.oops.model.User;
import pub.guoxin.oops.vo.ResultVo;
import pub.guoxin.oops.vo.ResultVoBuilder;

import javax.validation.Valid;

/**
 * Created by guoxin on 17-11-5.
 */
@RestController
@RequestMapping(OopsPathConstants.COMPANY_PATH)
public class CompanyController {

    @Autowired
    private ResultVoBuilder builder;
    @Autowired
    private CompanyService companyService;

    @ApiOperation(value = "添加公司", notes = "添加公司(权限: 游客)")
    @PostMapping(value = "/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @PreAuthorize(value = "hasAnyRole('VISITOR')")
    public ResultVo add(@InjectUser User user, @Valid @RequestBody CompanyVo companyVo) {
        Company company = companyVo.createCompany();
        companyService.add(company, user);
        return builder.buildSuccessResultInfo();
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN')")
    @ApiOperation(value = "更新公司信息", notes = "更新公司信息(权限: 公司管理员)")
    @PutMapping(value = "/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultVo update(@InjectUser User user, @Valid @RequestBody Company company) {
        if (!company.getId().equals(user.getCompanyId())) {
            return builder.buildBadRequestResultInfo();
        }
        Company update = companyService.update(company, user);
        return builder.buildSuccessResultInfo(update);
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN, USER')")
    @ApiOperation(value = "获得公司", notes = "获得公司(权限: 公司管理员, 公司子帐户)")
    @GetMapping(value = "/", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResultVo get(@InjectUser User user) {
        if (Strings.isNullOrEmpty(user.getCompanyId())) {
            return builder.buildBadRequestResultInfo("您尚未注册完成");
        }
        Company company = companyService.one(user.getCompanyId());
        return builder.buildSuccessResultInfo(company);
    }

}
